/**
 * eFashion ABTest Tracking SDK
 * author: jabez.huang
 * version: v1.0
 */

import {
  MERCHANT_INFO,
  CUSTOMER_INFO
} from '@/utils/constant';
import api from '@/api/api.js';
const GATEWAYIDJSON = {
  formal: 'efc-sg-prod-9g2vqh1q007068d1',
  trial: 'efc-sg-test-tke-8gsfog1ydae06fe0'
}
class EFSABTestTracking {
  constructor() {
    if (EFSABTestTracking.prototype.Instance === undefined) {
      EFSABTestTracking.prototype.Instance = this
    }
    return EFSABTestTracking.prototype.Instance
  }

  /**
   * 获取实验版本
   *  {
   *    path: "pages/home/home", merchantId: 100000005, storeId: 8,
   *    experimentId: 11,
   *    version: "A"
   *    versionParams: "?param=aaa" //TODO 尚无实现自动拼接到每个页面参数中
   *    versionScript: "{\"state\":{\"xxx\": \"red\"}}"  //versionScript.state,基于MVVM状态管理控制页面行为/样式
   *  }
   *  @param {Object} path 2021-07大改后，此列暂未使用
   */
  async getExperimentABTesting(path) {
    // let pathData = path.substring(path.lastIndexOf('/'))
    let host = api.baseUrl.substring(8)
    var pathData = path;
    return new Promise((resolve, reject) => {
      if(api.environment == 'formal') {
        wx.cloud.callContainer({
          path: "/cloud-optimize-service/customer/experiment/shuffle",
          method: 'GET',
          data: {
            merchant_id: uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
            store_id: uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
            path: pathData,
            targets: JSON.stringify(uni.getStorageSync("ABTargets")),
            user_ssid: uni.getSystemInfoSync().deviceId
          },
          timeout: 5000,
          header: {
            'Content-Type': 'application/json',
            'X-WX-EXCLUDE-CREDENTIALS': 'unionid, cloudbase-access-token, openid',
            'X-WX-GATEWAY-ID': GATEWAYIDJSON[api.environment],
            'HOST': host
          },
          success: res => {
            if (res.data.code == 200 && !!res.data.data) {
              let data = res.data.data;
              //存储到globalData中
              let app = getApp();
              app.globalData.abConfig = data;
              app.globalData.abGetDone = true;
              //存储到Storage中
              uni.setStorageSync('ABVersion_' + data.path, res.data.data); // TODO 赞未使用，无用
              uni.setStorageSync('abId', res.data.data.experimentId);
              uni.setStorageSync('abVersion', res.data.data.version);
              // efs_ab.setTrackingData( data ); //TODO 和tracking结合后，不在需要此方法

              resolve(data.version);
              // resolve(data.versionScript);
            } else {
              resolve(null);
            }
          }
        });
      } else {
        uni.request({
                url: api.baseUrl + "/cloud-optimize-service/customer/experiment/shuffle",
                method: 'GET',
                data: {
                  merchant_id:uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
                  store_id:uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
                  path:pathData,
                  targets: JSON.stringify( uni.getStorageSync("ABTargets") ),
                  user_ssid: uni.getSystemInfoSync().deviceId
                },
                timeout: 5000,
                header: {
                  'Content-Type': 'application/json'
                },
                success: res=>{
                  if(res.data.code == 200 && !!res.data.data){
                    let data = res.data.data;
                    //存储到globalData中
                    let app = getApp();
                    app.globalData.abConfig = data;
                    app.globalData.abGetDone = true;
                    // console.info("Get abtest data done,abConfig:" + JSON.stringify(data))
                    //存储到Storage中
                    uni.setStorageSync('ABVersion_'+data.path, res.data.data ); // TODO 赞未使用，无用
                    uni.setStorageSync('abId', res.data.data.experimentId);
                    uni.setStorageSync('abVersion', res.data.data.version);
                    // efs_ab.setTrackingData( data ); //TODO 和tracking结合后，不在需要此方法

                    resolve(data.version);
                    // resolve(data.versionScript);
                  }else{
                    resolve(null);
                  }
                }
              });

      }
    })
  }

  /**
   * 每个页面onLoad时尝试从已获取的AB测试场景中获取数据填充页面。此方法针对home页面时尝试等待n秒。待优化
   * @param {Object} t
   */
  tryApplyAbConfigForPage(t, callback) {
    //为当前页面尝试应用ab测试中配置的数据
    if (getApp().globalData.abGetDone) {
      efs_ab.applyAbTestForPage(t, callback);
    } else {
      // console.info("ab loading，waiting ...")
      setTimeout(function() {
        // console.info("abGetDone:" + getApp().globalData.abGetDone)
        if (getApp().globalData.abGetDone) {
          efs_ab.applyAbTestForPage(t, callback);
        } else {
          // 若0.5秒后还没获取到abtest的配置，尝试1秒钟以后再次请求
          setTimeout(function() {
            // console.info("abGetDone:" + getApp().globalData.abGetDone)
            if (getApp().globalData.abGetDone) {
              efs_ab.applyAbTestForPage(t, callback);
            }
             // else
             //  console.info("abGetDone为false时等待获取abtest数据结束")
          }, 1000);
        }
      }, 500); //尝试等待3秒数 FIXME 对home的ab测试不友好，home页面先展示了一个样式，几秒后又变了一个样式。
    }
  } //#end of  tryApplyAbConfigForPage

  /**
   * 每个页面onLoad时尝试从已获取的AB测试场景中获取数据填充页面
   * @param {Object} t
   */
  async applyAbTestForPage(t, callback) {
    let path = t.$page.fullPath;
    // console.info("Try to apply abtest script for page:" + path);
    var pathWithoutPara = path;
    if (path.indexOf("?") > 0) {
      pathWithoutPara = path.substring(0, path.indexOf("?"))
    }
    // console.info("path：" + pathWithoutPara);
    if (getApp().globalData.abConfig) {
      // console.info("Has abConfig data,try to apply to page");
      let pageConfigs = getApp().globalData.abConfig.pageConfigs;
      if (pageConfigs) {
        // console.info("abConfig.pageConfigs:" + JSON.stringify(pageConfigs));
        for (var i in pageConfigs) {
          var pageConfig = pageConfigs[i];
          if (pageConfig.path === pathWithoutPara) {
            var script = JSON.parse(pageConfig.pageScript);
            // console.info("abtest data in callbak script:" + script);
            Object.assign(t.$vm.abstate, script.state);
            // console.info("Page applied abtest script:" + pathWithoutPara + ", now state:" + JSON.stringify(t
            // .abstate));

            if (callback) callback();
          }
        }
      }
    }
  } //#end of applyAbTestForPage

  // /**
  //  * 上报Trakcing数据
  //  * @Deprecated at 2021-07-02,被tracking的onShow代替
  //  */
  // async setTrackingData( data ){
  //   let res = await uni.request({
  //     url: api.baseUrl + "/cloud-tracking-service/customer/tracking/action/optimize",

  //     method: 'POST',
  //     data: {
  //       merchantId:uni.getStorageSync(MERCHANT_INFO).cloudMerchantId,
  //       storeId:uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId,
  //       action:"PAGE_VISIT",
  //       value:data.path,
  //       customerId: 0,
  //       data: data,
  //       experimentId: data.experimentId,
  //       uniqueId: uni.getSystemInfoSync().deviceId,
  //       versionName: data.version
  //     },
  //     timeout: 10000,
  //     header: {
  //       'Content-Type': 'application/json'
  //     },
  //     success: res=>{
  //     }
  //   });
  // }

  proxyVue(t, e) {
    /* void 0 !== t.mixin && t.mixin({
      created: function() {
        let t = this.$root;
        t.$mp && "page" === t.$mp.mpType ? t.$mp.page && (e.vueRootVMs[t.$mp.page.route] = t) : "page" === t.mpType &&
          "page" === this.mpType && t.$mp.page
          && efs_ab.getExperimentShuffle(t.$mp.page.route)
        console.log( 'created' );
      }
    }) */
  }

  /**
   * 初始化Target信息
   */
  init(data) {
    let target = new Target();
    let targetData = target.getTarget();
    uni.setStorageSync("ABTargets", targetData);
    // this.proxyVue( data.vue, this );

    // //try to get abtest config
    // //*注意：当小程序尚无获取店铺信息时（或叫做首次使用），不进行ab测试。
    // //原因是home页面想应用ab测试数据，但abtest数据可能还没获取到，
    // //若像tryApplyAbConfigForPage方法中那样等待3秒再加载测试时，home页面会加载2次，体验不好
    // //没有好办法，所以将获取abtest数据的请求提前
    // if (uni.getStorageSync(MERCHANT_INFO) != "") {
    //   efs_ab.getExperimentABTesting("");
    // }
  }
}

//获取受众规则
class Target {
  targetLists = [];
  systemInfo = uni.getSystemInfoSync();
  getBrand() {
    let TARGET_ID = 5;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": this.systemInfo.brand
    });
  }
  getPlatform() {
    let TARGET_ID = 8;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": this.systemInfo.platform
    });
  }
  getSystemVersion() {
    let TARGET_ID = 7;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": this.systemInfo.system
    });
  }
  getWechatSDKVersion() {
    let TARGET_ID = 3;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": this.systemInfo.SDKVersion
    });
  }
  getWechatVersoin() {
    let TARGET_ID = 12;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": this.systemInfo.version
    });
  }
  getScreen() {
    let TARGET_ID = 6;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": this.systemInfo.screenWidth + "*" + this.systemInfo.screenHeight
    });
  }
  getIpAddress() {
    let TARGET_ID = 4;
    this.targetLists.push({
      "targetId": TARGET_ID,
      "targetName": "abTarget",
      "targetValue": uni.getStorageSync("efs_tracking_ip")
    });
  }
  getNewUserLaunch() {
    let TARGET_ID = 10;
  }
  getUserCostsTotal() {
    let TARGET_ID = 11;
  }
  getTarget() {
    this.getBrand();
    this.getPlatform();
    this.getSystemVersion();
    this.getWechatSDKVersion();
    this.getWechatVersoin();
    this.getScreen();
    this.getIpAddress();
    return this.targetLists;
  }
}

const efs_ab = new EFSABTestTracking();
export default efs_ab
